package com.sam.wang.springframework.beans.factory.support;

import com.sam.wang.springframework.beans.BeansException;
import com.sam.wang.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 使用java自带反射来实例化对象
 * @author wangchen
 * @version 1.0
 * @date 2021/9/1 10:19
 **/
public class SimpleInstantiationStrategy implements InstantiationStrategy{
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctr, Object[] args) throws BeansException {
        Class clazz = beanDefinition.getBeanClass();
        try {
            // 是否有带参构造函数来进行不同初始化
            if (null != ctr) {
                return clazz.getDeclaredConstructor(ctr.getParameterTypes()).newInstance(args);
            } else {
                return clazz.getDeclaredConstructor().newInstance();
            }
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new BeansException("Failed to instantiate [" + clazz.getName() + "]", e);
        }
    }
}
